package com.heiyu.api.controller;

import com.google.common.collect.Lists;
import com.heiyu.api.request.ArticleListRequest;
import com.heiyu.api.request.ArticleMoodPutRequest;
import com.heiyu.api.request.QuickArtilceListRequest;
import com.heiyu.api.response.*;
import com.heiyu.api.response.market.list.BannerInfoIndex;
import com.heiyu.api.response.model.*;
import com.heiyu.constants.BannerPositionEnum;
import com.heiyu.constants.ResponseMsgEnum;
import com.heiyu.controller.ApiBaseController;
import com.heiyu.dao.*;
import com.heiyu.entity.*;
import com.heiyu.entity.Info;
import com.heiyu.utils.DateUtils;
import com.heiyu.utils.DefaultImgUtils;
import com.heiyu.utils.NullObjUtil;
import com.heiyu.utils.PageUtils;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.omg.IOP.ENCODING_CDR_ENCAPS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mountain on 18/6/12.
 */
@Api(description = "文章相关")
@RestController
@RequestMapping("api/v1/article")
public class ArticleController extends ApiBaseController{

    @Autowired
    private ArticleItemMapper articleItemMapper;
    @Autowired
    private ArticleInfoMapper articleInfoMapper;
    @Autowired
    private ArticleLikeMapper articleLikeMapper;
    @Autowired
    private BannerInfoMapper bannerInfoMapper;
    @Autowired
    private ArticleMarkRefMapper articleMarkRefMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private BigAuthorFollowMapper bigAuthorFollowMapper;
    @Autowired
    private UserArticleCollectMapper userArticleCollectMapper;
    @Autowired
    private ArticleAssessInfoMapper articleAssessInfoMapper;

    private final static Integer maxLine = 20;


    @ApiOperation(value = "item/list",notes = "资讯菜单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId",value = "父级菜单主键"),
            @ApiImplicitParam(name = "type",value = "菜单类别，1是一级，2是二级如此类推")
    })
    @RequestMapping(value = "item/list",method = RequestMethod.GET)
    public ItemListResponse itemList(@RequestParam(name = "parentId",required = false)Long parentId,@RequestParam(name = "type",required = false)String type){
        ItemListResponse response = new ItemListResponse();
        ItemListModel model = new ItemListModel();
        model.setList(Lists.newArrayList());
        ArticleItem item = new ArticleItem();
        if(!StringUtils.isEmpty(type)){
            item.setType(type);
        }
        if(parentId != null){
            item.setParentId(parentId);
        }
        List<ArticleItem> list = this.articleItemMapper.selectList(item);
        if(CollectionUtils.isNotEmpty(list)){
            ItemInfo info;
            int i=0;
            for(ArticleItem entity:list){
                i++;
                if(type.equals("1") && i==2){
                    info = new ItemInfo();
                    info.setImgUrl(entity.getImgUrl());
                    info.setUrl(entity.getUrl());
                    info.setItemId(10l);
                    info.setName("大咖说");
                    info.setType(entity.getType());
                    model.getList().add(info);
                }
                info = new ItemInfo();
                info.setImgUrl(entity.getImgUrl());
                info.setUrl(entity.getUrl());
                info.setItemId(entity.getId());
                info.setName(entity.getName());
                info.setType(entity.getType());
                model.getList().add(info);
            }
        }
        response.setData(model);
        response.success();
        return response;
    }

    @ApiOperation(value = "增加分享")
    @RequestMapping(value = "share",method = RequestMethod.GET)
    public CommonResponse shareArticle(@ModelAttribute ArticleMoodPutRequest request){
            CommonResponse response = new CommonResponse();
            ArticleInfo articleInfo = this.articleInfoMapper.selectPrimary(request.getArticleId());
            if(articleInfo == null){
                response.error("文章信息不存在");
            }else{
                articleInfo.setShareTimes(NullObjUtil.get(articleInfo.getShareTimes())+1);
                this.articleInfoMapper.updateById(articleInfo);
                response.success();
                response.getData().setData("http://api31.heiyu.pro/article/index.html?articleId="+request.getArticleId());
            }
            return response;
    }

    @ApiOperation(value = "文章列表")
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public ArticleListResponse list(@ModelAttribute ArticleListRequest request){
        ArticleListResponse response = new ArticleListResponse();
        response.success();
        ArticleListModel model  = new ArticleListModel();
        model.setList(Lists.newArrayList());
        Map<String,Object> param = PageUtils.newParam(request.getPageIndex(),request.getPageSize());
        if(request.getType()!= null && request.getType().equals("2")){
            param.put("isTop","1");
        }
        param.put("itemId",3);
        List<ArticleInfo> list;
        if(request.getArticleId() == null){
            list = articleInfoMapper.itemList(param);
        }else{
            param.put("articleId",request.getArticleId());
            list = articleInfoMapper.refArticleList(param);
        }
        if(CollectionUtils.isNotEmpty(list)){
            ArticleEntity entity;
            ArticleLike like = new ArticleLike();
            UserInfo userInfo;
            for(ArticleInfo info:list){
                userInfo = this.userInfoMapper.selectPrimary(info.getUserId());
                like.setArticleId(info.getId());
                entity = new ArticleEntity();
                entity.setArticleId(info.getId());
                if(userInfo != null){
                    entity.setAuthor(userInfo.getNickName());
                }
                entity.setTitle(info.getTitle());
                entity.setTimestamp(Integer.valueOf(info.getCreatedTime().getTime()/1000+""));
                like.setIsGood("1");
                entity.setGoodNum(articleLikeMapper.loveCount(like));
                like.setIsGood("0");
                entity.setBadNum(articleLikeMapper.loveCount(like));
                entity.setImgUrl(StringUtils.isEmpty(info.getImgUrl())?DefaultImgUtils.getDefaultImg():info.getImgUrl());
                model.getList().add(entity);
            }
        }

        response.setData(model);
        return response;
    }


    @ApiOperation(value = "banner/list",notes = "推荐页面广告列表")
    @RequestMapping(value = "banner/list",method = RequestMethod.GET)
    public NewsBannerListResponse bannerList(){
        NewsBannerListResponse response = new NewsBannerListResponse();
        BannerListModel model = new BannerListModel();
        model.setList(Lists.newArrayList());
        response.success();
        BannerInfo info = new BannerInfo();
        info.setPosition(BannerPositionEnum.TOP_NEWS);
        List<BannerInfo> list = this.bannerInfoMapper.selectList(info);
        if(CollectionUtils.isNotEmpty(list)){
            BannerInfoIndex entity;
            int i=0;
            for(BannerInfo bannerInfo:list){
                i++;
                entity = new BannerInfoIndex();
                entity.setImgUrl(bannerInfo.getImgUrl());
                entity.setTitle(bannerInfo.getTitle());
                entity.setTargetUrl(bannerInfo.getTargetUrl());
                entity.setStatus(bannerInfo.getStatus());
                model.getList().add(entity);
                if(i>=5){
                    break;
                }
            }
        }
        response.setData(model);
        return response;
    }


    @ApiOperation(value = "get",notes = "文章详情信息")
    @ApiImplicitParam(name = "articleId",value = "文章主键")
    @RequestMapping(value = "get",method = RequestMethod.GET)
     public ArticleDetailResponse get(@RequestParam Long articleId){
        ArticleDetailResponse response = new ArticleDetailResponse();
        response.success();
        UserInfo userInfo = getUser();
        ArticelDetailModel model  = new ArticelDetailModel();
        ArticleInfo info = this.articleInfoMapper.selectPrimary(articleId);
        UserInfo author;
        if(info != null){
            author = this.userInfoMapper.selectPrimary(info.getUserId());
            Map<String,Object> param;
            if(userInfo != null){
                param = PageUtils.newParam(1,20);
                param.put("authorId",author.getId());
                param.put("userId",userInfo.getId());
                model.setIsFocus(this.bigAuthorFollowMapper.count(param)>0?"1":"0");
                param.put("articleId",articleId);
                model.setIsCollect(this.userArticleCollectMapper.count(param)>0?"1":"0");
            }else{
                model.setIsFocus("0");
                model.setIsCollect("0");
            }
            //评论数量
            param = PageUtils.newParam(1,20);
            param.put("articleId",articleId);
            model.setAssessNum(this.articleAssessInfoMapper.count(param));
            ArticleLike like  = new ArticleLike();
            like.setArticleId(articleId);
            model.setArticleId(info.getId());
            model.setArticleSource("http://api31.heiyu.pro/article/index.html?articleId="+info.getId());
            if(author != null){
                model.setAuthorName(author.getNickName());
                model.setAvator(author.getAvator());
                if(!model.getAuthorName().contains("朋友们"))
                model.setAuthorId(author.getId());
            }
            model.setShortDesc(info.getShotDesc());
            model.setContent(info.getContent());
            model.setCreatedTime(DateUtils.format(info.getCreatedTime(),"MM-dd"));
            model.setTimestamp(Integer.valueOf(info.getCreatedTime().getTime()/1000+""));
            like.setIsGood("0");
            model.setBadNum(this.articleLikeMapper.loveCount(like));
            like.setIsGood("1");
            model.setGoodNum(this.articleLikeMapper.loveCount(like));
            model.setTitle(info.getTitle());
            model.setMarkList(Lists.newArrayList());
            model.setRefArticleList(Lists.newArrayList());
            model.setImgUrl(info.getImgUrl());

            ArticleMarkRef ref = new ArticleMarkRef();
            ref.setArticleId(articleId);
            List<ArticleMarkRef> markRefs = this.articleMarkRefMapper.selectList(ref);
            if(userInfo != null){
                like = new ArticleLike();
                like.setUserId(userInfo.getId());
                like.setArticleId(info.getId());
                List<ArticleLike> likeList = this.articleLikeMapper.selectList(like);
                if(CollectionUtils.isNotEmpty(likeList)){
                    model.setIsGood(likeList.get(0).getIsGood());
                }
            }

            if(CollectionUtils.isNotEmpty(markRefs)){
                for(ArticleMarkRef markRef:markRefs){
                    model.getMarkList().add(markInfoUtils.getMarkName(markRef.getMarkId()));
                }
                //查找关联文章
                param = PageUtils.newParam(1,3);
                param.put("articleId",articleId);
                param.put("itemId",info.getItemId());
                List<ArticleInfo> list = this.articleInfoMapper.refArticleList(param);
                ArticleEntity entity;
                for(ArticleInfo articleInfo:list){
                    like.setArticleId(articleInfo.getId());
                    entity = new ArticleEntity();
                    author = this.userInfoMapper.selectPrimary(articleInfo.getUserId());
                    entity.setArticleId(articleInfo.getId());
                    if(author != null){
                        entity.setAuthor(author.getNickName());
                    }
                    entity.setTitle(articleInfo.getTitle());
                    entity.setTimestamp(Integer.valueOf(articleInfo.getCreatedTime().getTime()/1000+""));
                    entity.setGoodNum(articleLikeMapper.loveCount(like));
                    entity.setImgUrl(StringUtils.isEmpty(articleInfo.getImgUrl())?DefaultImgUtils.getDefaultImg():articleInfo.getImgUrl());
                    model.getRefArticleList().add(entity);
                }
            }
        }
        response.setData(model);
        return response;
     }


     @ApiOperation(notes = "文章点赞",value = "文章电站")
     @RequestMapping(value = "article/mood/put",method = RequestMethod.POST)
     public CommonResponse articleMood(@RequestBody ArticleMoodPutRequest request){
                CommonResponse response = new CommonResponse();
                UserInfo userInfo  = getUser();
                if(userInfo == null){
                    response.error(ResponseMsgEnum.USER_NOT_LOGIN);
                }
                ArticleLike articleLike = new ArticleLike();
                articleLike.setArticleId(request.getArticleId());
                articleLike.setUserId(userInfo.getId());
                List<ArticleLike> list = articleLikeMapper.selectList(articleLike);
                if(CollectionUtils.isNotEmpty(list)){
                    for(ArticleLike like:list){
                        this.articleLikeMapper.delete(like.getId());
                    }
                }else{
                    articleLike.setIsGood(request.getMood());
                    articleLike.setIsDeleted("0");
                    articleLike.setCreatedTime(new Date());
                    articleLike.setModifyTime(new Date());
                    this.articleLikeMapper.insert(articleLike);
                }
                response.success();
                return response;
     }

     @ApiOperation(value = "quick/list",notes = "快讯列表")
     @RequestMapping(value = "quick/list",method = RequestMethod.GET)
     public QuickArticleResponse quickList(@ModelAttribute QuickArtilceListRequest request){
            QuickArticleResponse response = new QuickArticleResponse();
            UserInfo userInfo = getUser();
            response.success();
            response.setData(new ArticleListModel());
            response.getData().setList(Lists.newArrayList());
            Map<String,Object> param  = PageUtils.newParam(request.getPageIndex(),request.getPageSize());
            param.put("itemId",2);
            List<ArticleInfo> list = this.articleInfoMapper.itemList(param);
            if(CollectionUtils.isNotEmpty(list)){
                ArticleEntity entity;
                ArticleLike like = new ArticleLike();
                UserInfo author;
                List<ArticleLike> articleLikes;
                for(ArticleInfo info:list){
                    author = this.userInfoMapper.selectPrimary(info.getUserId());
                    like.setArticleId(info.getId());
                    entity = new ArticleEntity();
                    entity.setTitle(info.getTitle());
                    entity.setMaxLine(maxLine);
                    if(author!= null)
                    entity.setAuthor(author.getNickName());
                    entity.setTimestamp(Integer.valueOf(info.getCreatedTime().getTime()/1000+""));
                    entity.setArticleId(info.getId());
                    like.setIsGood("1");
                    entity.setGoodNum(this.articleLikeMapper.loveCount(like));
                    like.setIsGood("0");
                    entity.setBadNum(this.articleLikeMapper.loveCount(like));
                    entity.setContent(info.getContent());
                     like.setIsGood(null);
                     if(userInfo != null){
                         like.setUserId(userInfo.getId());
                         articleLikes = this.articleLikeMapper.selectList(like);
                         entity.setIsGood(CollectionUtils.isNotEmpty(articleLikes)?articleLikes.get(0).getIsGood():null);
                     }else{
                         entity.setIsGood(null);
                     }
                    response.getData().getList().add(entity);
                }
            }
            return response;
     }


}
